package com.yymagicer.config;

import org.apache.shardingsphere.api.sharding.standard.RangeShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingValue;

import java.util.*;

/**
 * <p>Description: some description </p>
 *
 * @author : xiaodong.yang
 * @date : 2023/12/22 17:16
 */
public class DateRangeShardingAlgorithm implements RangeShardingAlgorithm<Date> {

    @Override
    public Collection<String> doSharding(Collection<String> tbNames, RangeShardingValue<Date> rangeShardingValue) {
        // 获取逻辑表名称
        String logicTableName = rangeShardingValue.getLogicTableName();

        // between and 的起始值，需要处理只有最大值或者只有最小值的情况
        boolean hasLowerBound = rangeShardingValue.getValueRange().hasLowerBound();
        boolean hasUpperBound = rangeShardingValue.getValueRange().hasUpperBound();

        long max = 0;
        long min = 0;

        // 只有最小值，比如：id > x
        if (hasLowerBound && !hasUpperBound) {
            Date lower = rangeShardingValue.getValueRange().lowerEndpoint();
            // 直接大于最小值的表
            String suffix = getSuffix(lower);
            min = Long.parseLong(suffix);
            // 获取最大的日期表
            ArrayList<String> arrayList = new ArrayList<>(tbNames);
            String maxSuffix = arrayList.get(tbNames.size() - 1).split("_")[1];
            max = Long.parseLong(maxSuffix);

        } else if (!hasLowerBound && hasUpperBound) {
            // 只有最大值，比如：id < x
            Date upper = rangeShardingValue.getValueRange().upperEndpoint();
            String suffix = getSuffix(upper);
            max = Long.parseLong(suffix);
            // 获取最小的日期表
            ArrayList<String> arrayList = new ArrayList<>(tbNames);
            String maxSuffix = arrayList.get(0).split("_")[1];
            min = Long.parseLong(maxSuffix);
        } else {
            // 区间值情况
            Date lower = rangeShardingValue.getValueRange().lowerEndpoint();
            Date upper = rangeShardingValue.getValueRange().upperEndpoint();
            String lowerSuffix = getSuffix(lower);
            String upperSuffix = getSuffix(upper);
            min = Long.parseLong(lowerSuffix);
            max = Long.parseLong(upperSuffix);
        }
        // 拼接事实表名称
        return matchMinAndMax(min, max, logicTableName);
    }

    private List<String> matchMinAndMax(long lower, long upper, String logicTableName) {
        List<String> tableNameList = new ArrayList<>();
        for (long index = lower; index <= upper; index++) {
            String tableName = logicTableName + "_" + index;
            tableNameList.add(tableName);
        }
        return tableNameList;
    }

    /**
     * 获取逻辑表后缀
     *
     * @param date
     * @return
     */
    private String getSuffix(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int year = cal.get(Calendar.YEAR);
        return String.valueOf(year);
    }
}
